﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Web.UI.DataVisualization.Charting;
using System.Xml.Linq;
using System.Data.SqlClient;
using MLY.Bll;


namespace MLY.LTR
{
    public partial class _default : Bll.BasePage
    {
        public class AlertStruct
        {
            public string Name { get; set; }
            public string Id { get; set; }

        }

        public string[] Colors = { "#00A8EB", "#929396", "#57585B", "Green", "Yellow", "Gold", "Brown" };
        public List<AlertStruct> AlertIds;
        public int CurrentAlertColor = 0;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                FillInCurrentActivityChart();
                AlertsRepeaterDataSource.SelectParameters.Add("UserId", SessParam.UserId.ToString());
                AlertsListDataSource.SelectParameters.Add("UserId", SessParam.UserId.ToString());
                UploadPercentDataSource.SelectParameters.Add("OrganizationId", SessParam.OrganizationId.ToString());
                OnTimeDeliveryDataSource.SelectParameters.Add("Organization", SessParam.OrganizationId.ToString());
                OnTimeDeliveryDataSource.SelectParameters.Add("IsClient", SessParam.IsClient.ToString());
                SupplierYieldDataSource.SelectParameters.Add("OrganizationId", SessParam.OrganizationId.ToString());
                SupplierYieldDataSource.SelectParameters.Add("IsClient", SessParam.IsClient.ToString());
                LoadCharts();
                if (Session["OrganizationId"] != null)
                    LastOrganizationalUpload.Text = Dictionary.Translate("Master.LastUpload") + ": " +
                       UploadLog.getLastUpload(int.Parse(Session["OrganizationId"].ToString()));
            }


        }

        protected void FillInCurrentActivityChart()
        {
            int orgId = SessParam.OrganizationId;
            bool IsClient = SessParam.IsClient;
            int X, Y;
            int index = 1;
            using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["MLYConnectionString"].ConnectionString))
            {
                SqlCommand cmd = new SqlCommand("SCCOver_CurrentActivityGraphData", conn);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.Add("OrgId", SqlDbType.Int);
                cmd.Parameters["OrgId"].Value = orgId;

                cmd.Parameters.Add("IsClient", SqlDbType.Bit);
                cmd.Parameters["IsClient"].Value = IsClient;

                SqlDataReader reader;

                try
                {
                    conn.Open();

                    reader = cmd.ExecuteReader();
                    if (reader.HasRows)
                        while (reader.Read())
                        {
                            System.Web.UI.DataVisualization.Charting.CustomLabel CustomLabel =
                                        new System.Web.UI.DataVisualization.Charting.CustomLabel
                            {
                                Text = reader.GetString(0),
                                FromPosition = index - 0.5,
                                ToPosition = index + 0.5
                            };
                            if (CustomLabel.Text.Length > 15)
                                CustomLabel.Text = CustomLabel.Text.Substring(0, 15);

                            X = reader.GetInt32(1);
                            Y = reader.GetInt32(2);
                            if (X > 0 || Y > 0)
                                CurrentActivityChart.ChartAreas["ChartArea1"].AxisX.CustomLabels.Add(CustomLabel);

                            if (X > 0)
                                CurrentActivityChart.Series[0].Points.AddXY((double)index, double.Parse(reader.GetInt32(1).ToString()));
                            if (Y > 0)
                                CurrentActivityChart.Series[1].Points.AddXY((double)index, double.Parse(reader.GetInt32(2).ToString()));

                            index++;
                        }
                }
                catch (Exception ex)
                {
                    Log.WriteError("FillInCurrentActivityChart failed with error", ex);
                }
                finally
                {
                    conn.Close();
                }
            }
        }

        protected string ReturnAlertColorDiv()
        {
            string ReturnValue = "<div style=\"width:20px; height:20px; float:left; margin:0px 3px 0px 3px; background-color:"
                + ReturnCurrentColor() + ";\"></div>";
            return ReturnValue;
        }

        #region LoadCharts

        private void LoadCharts()
        {
            //InitAlertIds();
            CrateChartSeries(0, 5, Alerts05Chart, Totals05Literal, Totals05Label);
            CrateChartSeries(5, 10, Alerts610Chart, Totals610Literal, Totals610Label);
            CrateChartSeries(11, 1000, Alerts1015Chart, Totals1015Literal, Totals1015Label);
            CurrentAlertColor = 0;
        }

        //private void InitAlertIds()
        //{
        //    using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["MLYConnectionString"].ConnectionString))
        //    {
        //        AlertIds = new List<AlertStruct>();
        //        SqlCommand cmd = new SqlCommand("AlertGetUserAlerts", conn);
        //        cmd.CommandType = CommandType.StoredProcedure;
        //        cmd.Parameters.Add("UserId", SqlDbType.Int);
        //        cmd.Parameters["UserId"].Value = SessParam.UserId;


        //        SqlDataReader reader;

        //        try
        //        {
        //            conn.Open();
        //            reader = cmd.ExecuteReader();
        //            if (reader.HasRows)
        //                while (reader.Read())
        //                {
        //                    AlertStruct alrt = new AlertStruct();
        //                    alrt.Id = reader.GetInt32(0).ToString();
        //                    alrt.Name = reader.GetString(1);
        //                    AlertIds.Add(alrt);
        //                }
        //        }
        //        catch (Exception ex)
        //        {
        //            Log.WriteError("InitAlertIds failed with error", ex);
        //        }
        //        finally
        //        {
        //            conn.Close();
        //        }
        //    }
        //}

        private void  CrateChartSeries(int daysMin, int daysMax, Chart chart, 
            Literal TotalsLiteral, Label CriticalsLabel)
        {
            int Normal, Critical;
            int Total = 0, TotalCritical = 0;
            int GroupNum = 0;
            
            CurrentAlertColor = 0;
            using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["MLYConnectionString"].ConnectionString))
            {
                SqlCommand cmd = new SqlCommand("SCCover_ReadAlertGraphData", conn);
                cmd.CommandType = CommandType.StoredProcedure;
                SqlDataReader reader;

                cmd.Parameters.Add("UserId", SqlDbType.Int);
                cmd.Parameters.Add("Mindays", SqlDbType.Int);
                cmd.Parameters.Add("MaxDays", SqlDbType.Int);

                cmd.Parameters["UserId"].Value = SessParam.UserId;
                cmd.Parameters["Mindays"].Value = daysMin;
                cmd.Parameters["MaxDays"].Value = daysMax;

                try
                {
                    conn.Open();
                    reader = cmd.ExecuteReader();
                    if (reader.HasRows)
                    {
                        //chart.ChartAreas[0].AxisX.CustomLabels.Add(new CustomLabel { Text = "", FromPosition = 0.5, ToPosition = 1.5 });

                        while (reader.Read())
                        {
                            Normal = reader.GetInt32(0);
                            Critical = reader.GetInt32(1);
                            Total += Normal;
                            Total += Critical;
                            TotalCritical += Critical;

                            //if (GroupNum > 0)
                            //{
                            //    Series sep = chart.Series.Add("Separator" + GroupNum.ToString());
                            //    sep.ChartType = SeriesChartType.Line;
                            //    sep.Color = System.Drawing.Color.White;
                            //    sep.Points.AddXY(1, 0);
                            //    sep.IsValueShownAsLabel = false;
                            //}

                            Series S_Normal = chart.Series.Add("Normal" + GroupNum.ToString());
                            S_Normal.Color = System.Drawing.ColorTranslator.FromHtml(ReturnCurrentColor());
                            S_Normal.ChartType = SeriesChartType.StackedColumn;
                            S_Normal["StackedGroupName"] = GroupNum.ToString();
                            S_Normal.IsValueShownAsLabel = true;
                            S_Normal.SmartLabelStyle.AllowOutsidePlotArea = LabelOutsidePlotAreaStyle.No;
                            S_Normal.SmartLabelStyle.IsMarkerOverlappingAllowed = false;
                            if (Normal >= 5)
                            {
                                S_Normal.LabelForeColor = System.Drawing.Color.White;
                                S_Normal["BarLabelStyle"] = "Center";
                            }
                            else
                            {
                                S_Normal.LabelForeColor = System.Drawing.Color.Black;
                                S_Normal["BarLabelStyle"] = "Outside";
                            }

                            
                            Series S_Critical = chart.Series.Add("Critical" + GroupNum.ToString());
                            S_Critical.Color = System.Drawing.Color.FromName("Red");
                            S_Critical.ChartType = SeriesChartType.StackedColumn;
                            S_Critical["StackedGroupName"] = GroupNum.ToString();
                            S_Critical.IsValueShownAsLabel = true;
                            S_Critical.SmartLabelStyle.AllowOutsidePlotArea = LabelOutsidePlotAreaStyle.Yes;
                            S_Critical.SmartLabelStyle.IsMarkerOverlappingAllowed = true;
                            S_Critical.LabelForeColor = System.Drawing.Color.Black;
                            S_Critical["BarLabelStyle"] = "Left";
                            
                            
                            S_Normal.Points.AddXY(1, (double)(Normal));
                            if (Critical > 0)
                                S_Critical.Points.AddXY(1, (double)Critical);

                            GroupNum++;

                        }

                    }
                    TotalsLiteral.Text = Total.ToString();
                    if (TotalCritical > 0)
                    {
                        CriticalsLabel.Text = "/" + TotalCritical.ToString();
                    }
                    else
                    {
                        CriticalsLabel.Visible = false;
                    }
                }
                catch (Exception ex)
                {
                    Log.WriteError("InitAlertIds failed with error", ex);
                }
                finally
                {
                    conn.Close();
                }
            }
        }

        protected void LoadOnTimeDeliveryChart(object sender, RepeaterItemEventArgs e)
        {
            try
            {
                double Percentage = double.Parse((e.Item.FindControl("DataHiddenField") as HiddenField).Value);
                Chart ch = (e.Item.FindControl("OnTimeDeliveryChart") as Chart);
                ch.Series[0].CustomProperties = "DoughnutRadius=45,PieStartAngle=270";
                Literal l = (e.Item.FindControl("PercentageLitetal") as Literal);
                l.Text = Percentage.ToString() + "%";
                //DataPoint Point = new DataPoint();
                //Point.XValue = Percentage;
                //Point.Color = GetPercentColor(Percentage);
                //ch.Series[0].Points.Add(Point);
                //DataPoint Completion = new DataPoint();
                //Completion.XValue = 100 - Percentage;
                ch.Series[0].Points.AddY(Percentage);
                ch.Series[0].Points.AddY(100 - Percentage);
                ch.Series[0].Points[0].Color = GetPercentColor(Percentage);
                ch.Series[0].Points[0].CustomProperties = "OriginalPointIndex=0";
                ch.Series[0].Points[0].LabelForeColor = System.Drawing.Color.White; 
                ch.Series[0].Points[1].Color = System.Drawing.ColorTranslator.FromHtml("#BCBDC0");
                ch.Series[0].Points[1].CustomProperties = "OriginalPointIndex=1";
            }
            catch { }
        }

        protected string YieldDivTitle(object Percentage)
        {
            try
            {
                int p = int.Parse(Percentage.ToString());
                if (p < 50)
                    return "<div class=\"red\">";
            }
            catch
            { }
            return "<div>";
        }

        protected string YieldDivLength(object Percentage)
        {
            try
            {
                int p = int.Parse(Percentage.ToString());
                return ("<em style=\"width:" + p + "%;\">" + p + "%</em>");
            }
            catch
            { }
            return "<em style=\"width:100%;\">100%</em>";
            
        }

        #endregion

        private string ReturnCurrentColor()
        {
            string ReturnValue = Colors[CurrentAlertColor];
            CurrentAlertColor++;
            if (CurrentAlertColor == Colors.Length)
                CurrentAlertColor = 0;
            return ReturnValue;
        }

        private System.Drawing.Color GetPercentColor(double Percentage)
        {
            if (Percentage <= 70)
                return System.Drawing.ColorTranslator.FromHtml("#C84428");
            return System.Drawing.ColorTranslator.FromHtml("#C2CA77");
        }
    
    }
}
